package com.example.safeassistan.my.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.utile.ToastUtil;
import org.json.JSONException;
import org.json.JSONObject;

public class CodeInput_Activity extends BaseActivity implements View.OnClickListener {
    private static final int CODE_ING = 1;//已发送，倒计时
    private static final int CODE_REPEAT = 2;//重新发送
    private int TIME = 60;// 倒计时60s
    private TextView tvSure;
    private TextView tvTimer;
    private EditText etMsgCode;
    private String msgCode="";
    private String phone = "";
    private TextView tvPhone;

    public static void actionStart(Context context,String phone) {
        Intent intent = new Intent(context, CodeInput_Activity.class);
        intent.putExtra("phone",phone);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tvTimer:
                getMobileMsgCode();
                break;
            case R.id.tvSure:
                checkMsgCode();
                break;
        }
    }

    /**
     *校验手机号
     */
    private void checkMsgCode() {
        JSONObject object = new JSONObject();
        try {
            object.put("code",msgCode);
            object.put("phone", phone);
            object.put("type", "2");//类型  1修改绑定手机号 2修改密码

        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(this).doPost(UrlConstants.checkCode, "", object, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        ActivityModifyPassword.actionStart(getContext(),msgCode,phone);
                    }else {
                        ToastUtil toastUtil=new ToastUtil(getContext(),R.layout.popu_success1,message,1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e(TAG,msg);
            }
        });
    }

    @Override
    protected void init(Bundle savedInstanceState) {setAndroidNativeLightStatusBar(true); }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_codeinput;
    }

    @Override
    protected void initView() {
        setBackVisible(true);
        setTitleText("验证手机号");
        tvPhone=findViewById(R.id.tvPhone);
        tvTimer=findViewById(R.id.tvTimer);
        tvTimer.setOnClickListener(this::onClick);
        phone=getIntent().getStringExtra("phone");
        String p=phone.substring(3,7);
        tvPhone.setText("请输入手机号"+phone.replace(p,"****")+"收到的验证码");
        tvSure=findViewById(R.id.tvSure);
        tvSure.setOnClickListener(this);
        etMsgCode=findViewById(R.id.etMsgCode);
        etMsgCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    msgCode = s.toString().trim();
                } catch (Exception e) {
                    msgCode="";
                }
                if(msgCode.length()>=4){
                    tvSure.setClickable(true);
                    tvSure.setBackgroundResource(R.drawable.login_checked_bg);
                }else {
                    tvSure.setClickable(false);
                    tvSure.setBackgroundResource(R.drawable.login_unchecked_bg);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        getMobileMsgCode();
    }



    /**
     * 获取手机验证码
     */
    private void getMobileMsgCode() {
        JSONObject object = new JSONObject();
        try {
            object.put("phone", phone);
            object.put("type", "2");//类型  1修改绑定手机号 2修改密码

        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(this).doPost(UrlConstants.sms_send, "", object, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model = (BaseModel) obj;
//                                new Thread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        for (int i = 60; i > 0; i--) {
//                                            handler.sendEmptyMessage(CODE_ING);
//                                            if (i <= 0) {
//                                                break;
//                                            }
//                                            try {
//                                                Thread.sleep(1000);
//                                            } catch (InterruptedException e) {
//                                                e.printStackTrace();
//                                            }
//                                        }
//                                        handler.sendEmptyMessage(CODE_REPEAT);
//                                    }
//                                }).start();
                            etMsgCode.setText(model.getResult().toString());
                            msgCode=model.getResult().toString();
                        }
                    }else {
                        ToastUtil toastUtil=new ToastUtil(getContext(),R.layout.popu_success1,message,1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e(TAG,msg);
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_ING:
                    tvTimer.setText(--TIME + "s");
                    break;
                case CODE_REPEAT:
                    tvTimer.setText("重新获取");
                    tvTimer.setTextColor(getResources().getColor(R.color.white));
                    tvTimer.setClickable(true);
                    TIME = 60;
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }
}
